﻿using UnityEngine;
using CustomGUI;
using System.Collections.Generic;
using System.IO;
using MiniJSON;

public class MainMenuScript : MonoBehaviour
{
	public GameObject containerPrefab;

	GameObject dataContainer;
	GameState gameState;
	GUIButton playButton;
	GUIButton scoreButton;

	readonly string sceneName = "MainMenu";
	string filePath;
	string jsonString;
	Dictionary<string,System.Object> dict;

	void Start ()
	{
		playButton = new GUIButton(0, 65, 65, 20, 20, "Play Game!", GUICallback);
		//scoreButton = new GUIButton(1, 40, 60, 20, 20, "High Score", GUICallback);
		if(GameObject.Find("DataContainer") == null)
		{
			dataContainer = Instantiate(containerPrefab, new Vector3(0,0,-9.9f), Quaternion.identity) as GameObject;
			DontDestroyOnLoad(dataContainer);
			dataContainer.name = "DataContainer";
		}
		else
		{
			dataContainer = GameObject.Find("DataContainer");
			DontDestroyOnLoad(dataContainer);
		}

		gameState = dataContainer.GetComponent<GameState>();
		gameState.CurrentScene = this.sceneName;

		filePath = Application.persistentDataPath + "\\data.json";
		/*if(!File.Exists(filePath))
		{
			Debug.Log("File not found!\nCreating a new data file at " + filePath + ".");
			var file = File.CreateText(filePath);
			dict = new Dictionary<string,System.Object>();
			for(int i = 1; i <= 10; i++)
			{
				dict.Add(i.ToString(), (System.Object)0);
			}
			jsonString = MiniJSON.Json.Serialize(dict);
			file.Write(jsonString);
			file.Close();
			dataContainer.GetComponent<GameState>().score = (System.Object)dict;
		}
		else
		{
			Debug.Log("Found data file at " + filePath + ".");
			var file = File.OpenText(filePath);
			jsonString = file.ReadLine();
			file.Close();
			dataContainer.GetComponent<GameState>().score = MiniJSON.Json.Deserialize(jsonString);
		}*/
	}

	void GUICallback(int id, Dictionary<string, string> callbackRes)
	{
		gameState.LastScene = this.sceneName;
		switch(id)
		{
			case 0:
				Application.LoadLevel("Game");
				break;
			case 1:
				Application.LoadLevel("HighScore");
				break;
		}
	}
}
